package com.fjnu.dao;

import com.fjnu.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CategoryDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询所有分类
     */
    public List<Category> selectAll() {
        String sql = "SELECT id, category_name, description, create_time FROM category ORDER BY create_time DESC";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Category.class));
    }

    /**
     * 新增类别
     * 规则：无显式参数校验，但需确保类别名非空（业务隐含要求），成功返回 1，失败返回 0
     */
    public int insert(Category category) {
        if (category.getCategoryName() == null) {
            return 0;
        }
        String sql = "INSERT INTO category(category_name, description, create_time) " +
                "VALUES(?, ?, NOW())";
        return jdbcTemplate.update(sql,
                category.getCategoryName(),
                category.getDescription()); // description 可选，允许为 Null
    }

    /**
     * 删除类别
     * 规则：需确保 categoryId 非空；若类别关联文章，需先处理关联（避免外键约束错误），成功返回 1，失败返回 0
     */
    public int delete(Integer categoryId) {
        if (categoryId == null) {
            return 0;
        }
        // 1. 先查询该类别是否有关联文章（避免外键冲突）
        String checkSql = "SELECT COUNT(*) FROM article WHERE category_id = ?";
        Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, categoryId);
        if (count != null && count > 0) {
            return 0; // 有关联文章，删除失败
        }
        // 2. 无关联时删除类别
        String deleteSql = "DELETE FROM category WHERE id = ?";
        return jdbcTemplate.update(deleteSql, categoryId);
    }
}